#include "StdAfx.h"
#include "GlobalSocket.h"

CGlobalSocket::CGlobalSocket(void)
{

}

CGlobalSocket::~CGlobalSocket(void)
{
}
int CGlobalSocket::getWMSOCKET()
{
	return WM_SOCKET;
}

SOCKET CGlobalSocket::getSockClient()
{
	return this->sClient;
}

sockaddr_in CGlobalSocket::getSockAddr()
{
	return this->servAdd;
}
CString CGlobalSocket::getServerAddress() {
	return this ->sServAdd;
}

CString CGlobalSocket::initSocket(CString serverAddress)
{
	WORD wVersionRequested;
	WSADATA wsaData;
	wVersionRequested=MAKEWORD(2,2);
	int err=WSAStartup(wVersionRequested,&wsaData);
	if (err!=0)
	{
		return _T("Can't initialize socket");
	}
	sServAdd = serverAddress;
	return _T("");
}

CString CGlobalSocket::connectToServer(CString serverAddress)
{
	sClient = socket(AF_INET, SOCK_STREAM, 0);
    hostent* host=NULL;
	if (sClient == INVALID_SOCKET)
    {
        return _T("socket() failed");
    }
    servAdd.sin_family = AF_INET;
    servAdd.sin_port = htons(PORT);
	
    servAdd.sin_addr.s_addr = inet_addr(CT2A(serverAddress));

	//Neu dia chi IP khong phai dang so nhu "172.29.20.20" ma dang ten
	// Vi du nhu "www.yahoo.com" phai goi ham gethostbyname() de phan dai thanh IP
	if (servAdd.sin_addr.s_addr==INADDR_NONE){
		host = gethostbyname(CT2A(serverAddress));
        if (host == NULL)
        {
            return _T("Unable to resolve server");
        }
        CopyMemory(&servAdd.sin_addr, host->h_addr_list[0],
            host->h_length);
	}
	int err=connect(sClient,(struct sockaddr*)&servAdd,sizeof(servAdd));
	if (err==SOCKET_ERROR){
		return _T("Connect Failed. May be:\n1.Invalid Servername.\n2.Server is not running.");
	}
	return _T("Connect Successful!");
}
void CGlobalSocket::setServerAddress(CString serverAddress)
{
	sServAdd = serverAddress;
}
bool CGlobalSocket::closeSocket()
{
	return true;
}